<template>
  <el-form :model="article" :rules="rules" ref="article" label-width="110px" class="demo-article" enctype="multipart/form-data">
    <el-form-item label="文章标题" prop="title">
      <el-input v-model="article.title" minlength="10" maxlength="50" show-word-limit name="title"></el-input>
    </el-form-item>
    <article-editor ref="editor" :content="article.content" />
    <el-form-item label="文章分类" prop="article_type_id">
        <el-select v-model="article.article_type_id"  clearable filterable placeholder="请选择" name="article_type_id">
          <el-option
            v-for="item in article_type"
            :key="item.article_type_id"
            :label="item.type_name"
            :value="item.article_type_id">
          </el-option>
        </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('article')">立即发布</el-button>
      <el-button type="primary" @click="saveForm('article')">存为草稿</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import { updateArticle, getArticleById } from 'network/article'
  import { getArticleType } from 'network/articleType'

  import ArticleEditor from 'components/articleEditor/ArticleEditor'

  export default {
    name: 'Update',
    components: { ArticleEditor },
    data() {
      return {
        article: {
          title: '',
          article_type_id: '',
          content: ''
        },
        article_type: [],
        rules: {
          title: [
            { required: true, message: '请输入文章标题', trigger: 'blur' },
            { min: 10, max: 50, message: '长度在 10 到 50 个字符', trigger: 'blur' }
          ],
          article_type_id: [
            { required: true, message: '请选择文章分类', trigger: 'change'}
          ]
        }
      }
    },
    methods: {
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 获取富文本编辑器内输入的文章内容
            let content = this.$refs['editor'].editor.getHtml()
            // 判断内容是否为空，为空则输出错误信息
            if (!content) return this.$message({
              type: 'error',
              message: '请输入文章内容！'
            })
            let formData = new FormData()
            formData.append('article_id', this.article.article_id)
            formData.append('title', this.article.title)
            formData.append('content', content)
            formData.append('article_type_id', this.article.article_type_id)
            formData.append('state', 1)
            // 调用修改文章接口
            updateArticle(formData).then(res => {
              if (res.status === 1) {
                console.log(res.message)
                return this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              this.$message({
                type: 'success',
                message: '发表文章成功！'
              })
              // 重新获取数据
              this.getArticleById(this.article.article_id)
            })
          } else {
            this.$message({
              type: 'error',
              message: '请输入完整且正确的信息！'
            })
            return false;
          }
        })
      },

      // 存为草稿
      saveForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 获取富文本编辑器内输入的文章内容
            let content = this.$refs['editor'].editor.getHtml()
            // 判断内容是否为空，为空则输出错误信息
            if (!content) return this.$message({
              type: 'error',
              message: '请输入文章内容！'
            })
            let formData = new FormData()
            formData.append('title', this.article.title)
            formData.append('content', content)
            formData.append('article_type_id', this.article.article_type_id)
            formData.append('state', 0)
            // 调用修改文章接口
            updateArticle(formData).then(res => {
              if (res.status === 1) {
                console.log(res.message)
                return this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              this.$message({
                type: 'success',
                message: '添加草稿成功！'
              })
              // 重新获取数据
              this.getArticleById(this.article.article_id)
            })
          } else {
            this.$message({
              type: 'error',
              message: '请输入完整且正确的信息！'
            })
            return false;
          }
        })
      },

      // 重置表单
      resetForm() {
        // 重新获取文章未更改时的内容数据进行展示
        let id = this.$route.query.id
        this.getArticleById(id)
        // 让编辑器内容为获取到的 article.content
        if (this.article.content.indexOf('<p>') === -1) return this.$refs['editor'].html = `<p>${this.article.content}</p>`
        this.$refs['editor'].html = this.article.content
      },

      // 根据 id 获取文章数据
      getArticleById(id) {
        getArticleById(id).then(res => {
          if (res.status === 1) console.log(res.message)
          if (res.data) {
            this.article = res.data
          } else {
            this.article = []
            return this.$message({
              type: 'error',
              message: '获取数据失败！'
            })
          }
        })
      }
    },
    created() {
      // 获取 article_type
      getArticleType().then(res => {
        if (res.status === 1) console.log(res.message)
        if (res.data) {
          this.article_type = res.data
        } else {
          this.article_type = []
        }
      })
      // 获取 article
      let id = this.$route.query.id
      this.getArticleById(id)
    }
  }
</script>

<style scoped>
  .el-form {
    width: 1200px;
  }
</style>